import Vue from 'vue'
import {
  login,
  logout,
  phoneLogin,
  thirdLogin,
  queryPermissionsByUser,
  getComboEffectiveDate,
  getRoute,
  easywork
} from '@/api/login'
import {
  ACCESS_TOKEN,
  USER_NAME,
  USER_INFO,
  USER_AUTH,
  SYS_BUTTON_AUTH,
  UI_CACHE_DB_DICT_DATA,
  TENANT_ID,
  CACHE_INCLUDED_ROUTES,
  LING_YANG_ROLE_TYPE,
  INTERFACE_PREFIX,
} from '@/store/mutation-types'
import { welcome } from '@/utils/util'
// import { queryPermissionsByUser } from '@/api/api'
import { getAction } from '@/api/manage'

const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    tenantid: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    info: {},
    collapsed: false,
    routeTitle: '',
    routePath: '',
    interfacePrefix: {},
    currentPrefix: '',
    effectiveDate: [],
    collapsedAno: true,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_ROUTETITLE: (state, obj) => {
      state.routeTitle = obj.title
      state.routePath = obj.path
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_TENANT: (state, id) => {
      state.tenantid = id
    },
    setCollapsed: (state, collapsed) => {
      state.collapsed = collapsed
    },
    SET_INTERFACE_PREFIX: (state, interfacePrefix) => {
      state.interfacePrefix = interfacePrefix
    },
    SET_CURRENT_PREFIX: (state, currentPrefix) => {
      state.currentPrefix = currentPrefix
    },
    SET_EFFECTIVE_DATE: (state, effectiveDate) => {
      state.effectiveDate = effectiveDate
    },
    SET_COLLAPSED_ANO: (state, collapsedAno) => {
      state.collapsedAno = collapsedAno
    },
  },

  actions: {
    // CAS验证登录
    ValidateLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        getAction('/sys/tokenLogin', userInfo)
          .then(async (response) => {
            console.log('----cas 登录--------', response)
            if (response.success) {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              // 获取所有应用的接口前缀并存储
              let res = await getRoute(result.token, `/jksaas-mgt/mgt/newSys/permission/getRoute`)
              Vue.ls.set(INTERFACE_PREFIX, res.data.result, 7 * 24 * 60 * 60 * 1000)
              commit('SET_INTERFACE_PREFIX', res.data.result)
              resolve(response)
            } else {
              commit('SET_TOKEN', '')
              commit('SET_PERMISSIONLIST', [])
              Vue.ls.remove(ACCESS_TOKEN)
              Vue.ls.remove(USER_INFO)
              Vue.ls.remove(USER_NAME)
              Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
              Vue.ls.remove(CACHE_INCLUDED_ROUTES)
              Vue.ls.remove(TENANT_ID)
              Vue.ls.remove(LING_YANG_ROLE_TYPE)
              Vue.prototype.$Jmessage.error(response.message, 4)
              resolve(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((response) => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo)
          .then((response) => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetPermissionList({ commit, state }) {
      return new Promise((resolve, reject) => {
        let token = Vue.ls.get(ACCESS_TOKEN)
        let lingyangRoleType = Vue.ls.get(LING_YANG_ROLE_TYPE)
        getComboEffectiveDate(token).then((date) => {
          commit('SET_EFFECTIVE_DATE', date.data.result)
        })
        queryPermissionsByUser(token, lingyangRoleType)
          .then((response) => {
            // console.log('获取的权限：',response);
            if (response.data.code == 500) {
              // this.$antdMessage.error(response.data.message)
              // reject(response.data.message)
              // alert(response.data.message)
              reject(response.data)
              // console.error('获取的权限：', response.data.message);
              // Vue.$notification['error']({
              //   message: '登录失败',
              //   description: response.data.message,
              //   duration: 4,
              // })
            }
            const menuData = response.data.result.menu
            const authData = response.data.result.auth
            const allAuthData = response.data.result.allAuth
            // Vue.ls.set(USER_AUTH,authData);
            sessionStorage.setItem(USER_AUTH, JSON.stringify(authData))
            sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData))
            if (menuData && menuData.length > 0) {
              // update--begin--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
              menuData.forEach((item, index) => {
                if (item['children']) {
                  let hasChildrenMenu = item['children'].filter((i) => {
                    return !i.hidden || i.hidden == false
                  })
                  if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
                    item['hidden'] = true
                  }
                }
              })
              // console.log(" menu show json ", menuData)
              // update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
              commit('SET_PERMISSIONLIST', menuData)
            } else {
              reject('getPermissionList: permissions must be a non-null array !')
            }
            resolve(response.data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        let logoutToken = state.token
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(USER_INFO)
        Vue.ls.remove(USER_NAME)
        Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
        Vue.ls.remove(CACHE_INCLUDED_ROUTES)
        Vue.ls.remove(TENANT_ID)
        Vue.ls.remove(LING_YANG_ROLE_TYPE)
        // console.log('logoutToken: '+ logoutToken)
        logout(logoutToken)
          .then(() => {
            if (process.env.VUE_APP_SSO == 'true') {
              let sevice = 'http://' + window.location.host + '/'
              let serviceUrl = encodeURIComponent(sevice)
              window.location.href = process.env.VUE_APP_CAS_BASE_URL + '/logout?service=' + serviceUrl
            }
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    },
    // 第三方登录
    ThirdLogin({ commit }, param) {
      return new Promise((resolve, reject) => {
        thirdLogin(param.token, param.thirdType)
          .then((response) => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 易工作登录
    EasyWork({ commit }, param) {
      return new Promise((resolve, reject) => {
        // 修改前缀
        easywork(param.code)
          .then((response) => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },


    saveTenant({ commit }, id) {
      Vue.ls.set(TENANT_ID, id, 7 * 24 * 60 * 60 * 1000)
      commit('SET_TENANT', id)
    },
  },
}

export default user
